package server;

import inter.ServerInterface;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import model.Ga;
import model.Ghe;
import model.GioTau;
import model.Tau;
import model.Tuyen;
import controll.Controller;
import controll.Mapping;

public class Server extends UnicastRemoteObject implements ServerInterface{
	
	Mapping map = new Mapping();
	Controller controler = new Controller();
	
	protected Server() throws RemoteException {
		super();
	}

	public static void main(String args[]) {
		try {
			LocateRegistry.createRegistry(1099);

			Server server = new Server();

			Naming.rebind("RMI", server);

			System.out.println("Ready");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<Tuyen> getListTuyen() throws RemoteException {
		System.out.println("=============");
		List<Tuyen> list = null;
		try {
			list = map.getListTuyen();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println("----------5");
		return list;
	}

	@Override
	public List<Tau> getListTau(Tuyen tuyen) throws RemoteException {
		return map.getListTau(tuyen);
	}

	@Override
	public List<Ga> getListGaDi(Tau tau) throws RemoteException {
		List<GioTau> listGio = map.getGioTauList(tau);
		List<Ga> listGa = new ArrayList<Ga>();
		for (GioTau gioTau : listGio) {
			listGa.add(gioTau.getGaID());
		}
		return listGa;
	}

	@Override
	public List<Ga> getListGaDen(Ga gaDi, Tau tau) throws RemoteException {
		List<Ga> listGa = new ArrayList<Ga>();
		listGa.addAll(this.getListGaDi(tau));
		List<Ga> listGaDen = new ArrayList<Ga>();
		if(tau.getTuyenID().getHuong().equals("1")) {
			for (Ga ga : listGa) {
				if(ga.getGaID() > gaDi.getGaID()) {
					listGaDen.add(ga);
				}
			}
		} else {
			for (Ga ga : listGa) {
				if(ga.getGaID() < gaDi.getGaID()) {
					listGaDen.add(ga);
				}
			}
		}
		return listGaDen;
	}

	@Override
	public List<Ghe> getListGheTrong(Tau tau, Ga gaDi, Ga gaDen, Date ngay)
			throws RemoteException {
		// TODO Auto-generated method stub
		return controler.getListGheTrong(tau, ngay, gaDi, gaDen);
	}
	
	@Override
	public List<Tau> getListTau() throws RemoteException{
		return map.getListTau();
	}
}
